<template>
    <div class="cai">
        <div class="buttons">
            <div>
                <p>6、/index/api/getMediaList</p>
                <el-button type="primary" @click="getMediaListFun">获取流列表，可选筛选参数</el-button>
                <div v-if="list">
                    <!-- <li v-for="(item, index) in list" :key="index">
                        {{ item.originUrl }}
                    </li> -->
                    <el-table :data="list" style="width: 100%">
                        <el-table-column prop="stream" label="流id" width="160" />
                        <el-table-column prop="app" label="应用名" width="80" />
                        <el-table-column prop="schema" label="协议" width="80" />
                        <el-table-column prop="vhost" label="虚拟主机" width="180" />
                        <el-table-column prop="originUrl" label="Address" />
                    </el-table>
                </div>
            </div>
            <div>
                <p>8、/index/api/close_streams</p>
                <el-button type="success" @click="close_streamsFun">关闭流(目前所有类型的流都支持关闭)</el-button>
            </div>
            <div>
                <p>9、/index/api/getAllSession</p>
                <el-button type="primary" @click="getAllSessionFun">获取所有TcpSession列表</el-button>
            </div>
            <div>
                <p>12、/index/api/addStreamProxy</p>
                <el-button type="success" @click="addStreamProxyFun">动态添加rtsp/rtmp/hls/http-ts/http-flv拉流代理(只支持H264/H265/aac/G711/opus负载)</el-button>
                <el-button type="success" @click="addStreamProxyFun1">添加 rtsp 视频流 (第二个)</el-button>
            </div>
            <div>
                <p>13、/index/api/delStreamProxy(流注册成功后，也可以使用close_streams接口替代)</p>
                <el-button type="info" @click="delStreamProxyFun">关闭拉流代理</el-button>
            </div>
            <div>
                <p>14、/index/api/addFFmpegSource</p>
                <el-button type="info" @click="addFFmpegSourceFun">通过fork FFmpeg进程的方式拉流代理，支持任意协议</el-button>
            </div>
            <div>
                <el-button type="primary" @click="listRtpServerFun">获取openRtpServer接口创建的所有RTP服务器</el-button>
            </div>
            <div>
                <el-button type="danger" @click="getRtpInfoFun">获取rtp代理时的某路ssrc rtp信息</el-button>
            </div>
            <div>
                <div class="video_box">
                    <video id="video_player1" muted autoplay width="300" class="video"
                        src="http://127.0.0.1:9002/live/test_stream123.live.mp4">
                    </video>
                    <video id="video_player1" muted autoplay width="300" class="video"
                        src="http://127.0.0.1:9002/live/zhongtie_123.live.mp4">
                    </video>
                </div>
            </div>
            <div style="flex-direction:row; gap: 0;">
                <el-button type="success" @click="webSocketFun">WebSocket链接</el-button>
                <el-button type="danger" @click="beforeUnmount">WebSocket断开</el-button>
                <el-button type="success" @click="wsPlayerFun('ws://127.0.0.1:9002/live/test_stream123.live.mp4')">ws 播放 1</el-button>
                <el-button type="success" @click="wsPlayerFun('ws://127.0.0.1:9002/live/zhongtie_123.live.mp4')">ws 播放 2</el-button>
            </div>
            <div>
                <video id="video_player" ref="videoPlayer" controls autoplay width="640" height="360"></video>
            </div>
        </div>
        <div style="text-align: left;">
            <!-- {{ test }} -->
            {{ JSON.stringify(test, null, 2) }}
        </div>
    </div>
  </template>
  
  <script>
  // npm install ws //安装websoket 不用引入模块 在nodejs里面
  import axios from 'axios';

  // 导入 wsPlayer 类
  import wsPlayer from '@/utils/wsPlayer/wsPlayer';

  export default {
    name: 'video_cai',
    data() {
      return {
        key: 0,
  
        model: null, // 添加一个属性来保存模型的引用
        cylinderModel: null,
        cubeModel: null,

        MediaServerUrl: 'http://192.168.50.85:9002',
        MediaServerKey: 'aqxY9ps21fyhyKNRyYpGvJCTp1JBeGOM',

        list:null,
        test:'',
        setTimeoutId: null,

        websocket: null, // WebSocket实例

        mWsVideoPlayer: null,  // 用于保存 wsPlayer 实例

        videoUrl: '',
        videoPlayer: null,
        ws: null,
        frameQueue: [],
        sourceBuffer: null,
      };
    },
    props: {
      msg: String
    },
    mounted() {
    },
    methods: {

        // ws 用于开始播放
        wsPlayerFun(video_url) {
            let mVideoUrl = video_url;

            if (mVideoUrl.startsWith("ws://")) {
                // 如果已经有实例，则先关闭之前的实例
                if (this.mWsVideoPlayer) {
                try {
                    this.mWsVideoPlayer.close();
                } catch (e) {
                    console.log("wsPlayer close error:", e);
                }
                }
                // 创建新的 wsPlayer 实例并打开
                this.mWsVideoPlayer = new wsPlayer("video_player", mVideoUrl);
                this.mWsVideoPlayer.open();
            } else if (mVideoUrl.startsWith("http://")) {
                // 如果是 HTTP 视频，直接设置 src
                let videoElement = document.getElementById("video_player");
                videoElement.src = mVideoUrl;
            }
        },

        //获取openRtpServer接口创建的所有RTP服务器
        listRtpServerFun(){
            const url = this.MediaServerUrl+'/index/api/listRtpServer';
            const params = {
                secret: this.MediaServerKey,  // API 密钥
            };
            // 发送 POST 请求
            axios.get(url, { params })
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //功能：获取rtp代理时的某路ssrc rtp信息
        getRtpInfoFun(){
            const url = this.MediaServerUrl+'/index/api/getRtpInfo';
            const params = {
                secret: this.MediaServerKey,  // API 密钥
                stream_id: "test_stream123",  // 示例 SSRC 或流 ID（使用实际值）
            };
            // 发送 POST 请求
            axios.get(url, { params })
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //<p>14、/index/api/addFFmpegSource</p>
        //通过fork FFmpeg进程的方式拉流代理，支持任意协议
        addFFmpegSourceFun(){
            const url = this.MediaServerUrl+'/index/api/addFFmpegSource';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
                src_url:	'Y	FFmpeg拉流地址,支持任意协议或格式(只要FFmpeg支持即可)',
                dst_url:	'Y	FFmpeg rtmp推流地址，一般都是推给自己，例如rtmp://127.0.0.1/live/stream_form_ffmpeg',
                timeout_ms:	'Y	FFmpeg推流成功超时时间',
                enable_hls:	'Y	是否开启hls录制',
                enable_mp4:	'Y	是否开启mp4录制',
            };
        },
        //13、/index/api/delStreamProxy(流注册成功后，也可以使用close_streams接口替代)
        //关闭拉流代理
        delStreamProxyFun(){
            const url = this.MediaServerUrl+'/index/api/delStreamProxy';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
                key: '__defaultVhost__/live/test_stream123', //addStreamProxy接口返回的key
            };
            // 发送 POST 请求
            axios.post(url, data)
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //功能：动态添加rtsp/rtmp/hls/http-ts/http-flv拉流代理(只支持H264/H265/aac/G711/opus负载)
        addStreamProxyFun(){
            const url = this.MediaServerUrl+'/index/api/addStreamProxy';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
                vhost: "__defaultVhost__",  // 默认虚拟主机
                app: "live",  // 应用名
                stream: "test_stream123",  // 流 ID
                url: "rtsp://admin:Bywss123@192.168.50.15:554/h264/ch1/sub/av_stream",  // 拉流地址

                //ws://192.168.50.85:9002/live/test_stream123.live.mp4
                //ws://192.168.50.85:9002/live/test_stream123.live.flv
                //http://192.168.50.85:9002/live/test_stream123.live.mp4
                //http://192.168.50.85:9002/live/test_stream123.live.flv
                //rtsp://192.168.50.85:1554/live/test_stream123
                
                rtp_type : 0,
                enable_hls	: true, //	是否转换成hls-mpegts协议	
                enable_hls_fmp4	: true, //	是否转换成hls-fmp4协议	
                enable_mp4	: true, //	是否允许mp4录制	
                enable_rtsp	: true, //	是否转rtsp协议	
                enable_rtmp	: true, //	是否转rtmp/flv协议	
                enable_ts	: true, //	是否转http-ts/ws-ts协议	
                enable_fmp4	: true, //	是否转http-fmp4/ws-fmp4协议	
            };

            // 发送 POST 请求
            axios.post(url, data)
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
                if(response.data.msg == "This stream already exists"){
                    this.test += '目标流已经存在';
                }
                this.setTimeoutId = setTimeout(() => {
                    this.getMediaListFun();//获取流列表
                }, 1000);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        // 添加视频流
        addStreamProxyFun1(){
            const url = this.MediaServerUrl+'/index/api/addStreamProxy';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
                vhost: "__defaultVhost__",  // 默认虚拟主机
                app: "live",  // 应用名
                stream: "zhongtie_123",  // 流 ID
                url: "rtsp://admin:Bywss123@192.168.50.35:554/h264/ch1/sub/av_stream",  // 拉流地址
                rtp_type : 0,
                enable_hls	: true, //	是否转换成hls-mpegts协议	
                enable_hls_fmp4	: true, //	是否转换成hls-fmp4协议	
                enable_mp4	: true, //	是否允许mp4录制	
                enable_rtsp	: true, //	是否转rtsp协议	
                enable_rtmp	: true, //	是否转rtmp/flv协议	
                enable_ts	: true, //	是否转http-ts/ws-ts协议	
                enable_fmp4	: true, //	是否转http-fmp4/ws-fmp4协议	
            };

            // 发送 POST 请求
            axios.post(url, data)
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
                if(response.data.msg == "This stream already exists"){
                    this.test += '目标流已经存在';
                }
                this.setTimeoutId = setTimeout(() => {
                    this.getMediaListFun();//获取流列表
                }, 1000);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //获取所有TcpSession列表(获取所有tcp客户端相关信息)
        getAllSessionFun(){
            const url = this.MediaServerUrl+'/index/api/getAllSession';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
            };
            // 发送 POST 请求
            axios.post(url, data)
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //关闭流(目前所有类型的流都支持关闭)
        close_streamsFun(){
            const url = this.MediaServerUrl+'/index/api/close_streams';
            const data = {
                secret: this.MediaServerKey,  // API 密钥
                stream: "test_stream123",  // 流 ID
            };

            // 发送 POST 请求
            axios.post(url, data)
            .then(response => {
                console.log('请求成功:', response.data);
                this.test = '成功:' + JSON.stringify(response.data);
                this.test += '筛选命中的流个数:' + response.data.count_hit;
                this.test += '被关闭的流个数：' + response.data.count_closed;
                this.getMediaListFun();//获取流列表
            })
            .catch(error => {
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        //获取流列表，可选筛选参数
        getMediaListFun(){
            const url = this.MediaServerUrl+'/index/api/getMediaList'; //获取流列表
            const data = {
                secret: this.MediaServerKey,
                schema: "rtsp",
            };
            // 发送 POST 请求
            axios.post(url, data).then(response => {
                // 请求成功时的处理
                console.log('成功:', response.data);
                /* this.test = '成功:' + JSON.stringify(response.data); */
                this.list = response.data.data;
            })
            .catch(error => {
                // 请求失败时的处理
                console.error('请求失败:', error);
                this.test = '请求失败:' + error;
            });
        },
        /* getFun(){
            // 发送 GET 请求
            axios.get('http://127.0.0.1/live/test')
            .then(response => {
                this.apiData = response.data;
                this.loading = false;
            })
            .catch(error => {
                console.error("API 请求失败:", error);
                this.loading = false;
            });
        }, */

        // webSocket
        webSocketFun() {
            //const serverAddress = 'ws://192.168.50.85:9002/live/test_stream123.live.mp4';
            const serverAddress = 'ws://127.0.0.1:9002/live/camd30b5e1d10853.live.mp4';
            this.websocket = new WebSocket(serverAddress);

            this.websocket.onopen = () => {
                console.log('WebSocket connected', '执行开始');
            };

            this.websocket.onmessage = event => {
                console.log('Received message 告警:', event);
            };

            this.websocket.onclose = () => {
                console.log('WebSocket closed');
            };

            this.websocket.onerror = event => {
                console.error('WebSocket error:', event);
            };
        },
        // websocket断开链接
        beforeUnmount() { 
            if (this.websocket) {
                this.websocket.close();
            }
        },


    }
  }
  </script>
  
  <style lang='scss' scoped>
    .cai{
        padding: 60px 20px;
        display: flex;
    }
    .buttons{
        display: flex;
        flex-direction: column;
        gap: 10px;
        > div{
            display: flex;
            flex-direction: column;
            gap: 5px;
            > p{
                font-size: 12px;
                font-weight: bold;
                color: #999;
                padding: 0;
                margin: 0;
                text-align: left;
            }
        }
    }
    .video_box{
        float: left;
        border:solid 1px #666666;
        padding: 0;
        margin: 0;
        .video{
            display: inline-block;
            margin: 0;
            padding: 0;
            border:solid 1px #409eff;
            font-size: 0;
            margin-bottom: -4px
        }
        
    }

  </style>
  